package com.yicong.ants.ui.circle.ad;

import android.graphics.Rect;
import android.os.Build;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cchao.simplelib.core.JsonHelper;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity;
import com.cchao.simplelib.ui.adapter.StatefulBindMultiQuickAdapter;
import com.cchao.simplelib.util.StringHelper;
import com.kennyc.view.MultiStateView;
import com.yicong.ants.BR;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.circle.ViewedItem;
import com.yicong.ants.bean.common.MultiItemWrapper;
import com.yicong.ants.databinding.RecyclerBinding;
import com.yicong.ants.manager.ImageHelper;
import com.yicong.ants.manager.RouterHelper;
import com.yicong.ants.manager.ad.AntsAdHelper;
import com.yicong.ants.manager.config.ZzConfigs;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.utils.AmapHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 广告页面
 *
 * @author cchao
 * @version 2020-11-3 16:23:55
 */
public class AdViewedActivity extends BaseTitleBarActivity<RecyclerBinding> implements View.OnClickListener {

    StatefulBindMultiQuickAdapter<MultiItemWrapper> mAdapter;

    @Override
    protected int getLayout() {
        return R.layout.recycler;
    }

    @Override
    protected void initEventAndData() {
        initAdapter();
        setTitleText("我看过的社区广告");
        onLoadData();
    }

    private void initAdapter() {
        mDataBind.recycler.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new StatefulBindMultiQuickAdapter<MultiItemWrapper>(null) {

            @Override
            public Map<Integer, Integer> getTypeLayoutMap() {
                Map<Integer, Integer> map = new HashMap<>(8);
                map.put(1, R.layout.circle_ad_viewed_item);
                return map;
            }

            @Override
            protected void convert(DataBindViewHolder helper, MultiItemWrapper data) {
                switch (helper.getItemViewType()) {
                    case 1: // 左文右图
                        convertType1(helper, (ViewedItem) data.getObject());
                        break;
                }
            }

            private void convertType1(DataBindViewHolder helper, ViewedItem item) {
                helper.getBinding().setVariable(BR.bean, item);
                ImageHelper.setLayoutParamsWh(helper.getView(R.id.image)
                    , (int) (UiHelper.getScreenWidth() / 2.7f), 16, 9);
            }

            @Override
            public void loadPageData(int page) {
                loadPage(page);
            }

        };
        mAdapter.bindToRecyclerView(mDataBind.recycler);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            MultiItemWrapper itemWrapper = mAdapter.getData().get(position);
            ViewedItem item = (ViewedItem) itemWrapper.getObject();
            if (StringHelper.isNotEmpty(item.getLink())) {
                AntsAdHelper.clearAdInfo(AntsAdHelper.Position.All);

                // 能被路由
                if (RouterHelper.tryRoutePlatformUri(thisActivity, item.getLink())) {
                    return;
                }

                if (item.getLink().startsWith("http")) {
                    ZzConfigs.toWebActivityCheckLogin(mContext, "社区广告", item.getLink());
                }
            }
        });
        mDataBind.recycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int adapterPosition = parent.getChildAdapterPosition(view);
                outRect.bottom = UiHelper.dp2px(24);
                outRect.top = UiHelper.dp2px(0);
                if (adapterPosition == 0) {
                    outRect.top = UiHelper.dp2px(8);
                }
            }
        });
    }

    @Override
    protected void onLoadData() {
        loadPage(1);
    }

    void loadPage(final int page) {
        final Map<String, String> params = new HashMap<>();
        params.put("page", String.valueOf(page));
        params.put("page_size", String.valueOf(Constants.PAGE_SIZE));

        try {
            params.put("phoneBrand", Build.BRAND);
            AmapHelper.LocationInfo locationInfo = AmapHelper.getLocationInfo();
            if (locationInfo != null) {
                params.putAll(JsonHelper.toMap(JsonHelper.toJson(locationInfo), String.class));
            }
        } catch (Exception ex) {
            Logs.logException(ex);
        }

        if (page == 1) {
            mAdapter.setViewState(MultiStateView.VIEW_STATE_LOADING);
        }
        addSubscribe(RetrofitHelper.getApis().adViewed(params)
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                if (respBean.isCodeFail()) {
                    showToast(respBean.getMsg());
                    mAdapter.loadMoreComplete();
                }
                List<ViewedItem> data = respBean.getList();
                List<MultiItemWrapper> list = new ArrayList<>();
                for (ViewedItem datum : data) {
                    list.add(MultiItemWrapper.of(1, datum));
                }
                mAdapter.solvePagesData(list, page, Constants.PAGE_SIZE);
            }, RxHelper.getSwitchableErrorConsumer(mAdapter)));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }
}
